import _json
import requests
import csv
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
key = "*************"
today_time = time.strftime('%Y-%m-%d', time.localtime())
print(today_time)
print("请输入要查询城市,输入退出结束：")

def get_weather_data():
    title = ["城市", "更新时间", "天气情况", "体感温度", "温度", "相对湿度", "能见度"]
    place = ''
    with open('weather_today.csv', 'w', newline='')as f:
        writer = csv.writer(f)
        writer.writerow(title)
        while place != "退出":
            place = input("请输入要查询城市")
            if place == "退出":
                break
            url = 'https://free-api.heweather.net/s6/weather/now?location={0}&key=c9df4c192acb4b4ea541b71179126ba0'.format(
                place)
            res = requests.get(url).json()
            result = res['HeWeather6'][0]['now']
            location = res['HeWeather6'][0]['basic']
            time = res['HeWeather6'][0]['update']
            city = location['admin_area'] + location['location']
            cond = result['cond_txt']
            fl = result['fl']
            tmp = result['tmp']
            hum = result['hum']
            vis = result['vis']
            time = time['loc']
            writer.writerows([(city, time, cond, fl, tmp, hum, vis)])
    send_email()


def send_email():
    HOST = 'smtp.qq.com'
    SUBJECT = '%s日的天气预报信息，请查收' % today_time
    FROM = '2805193928@qq.com'
    TO = '3382583124@qq.com'
    message = MIMEMultipart('related')
    message_html = MIMEText("%s日份天气预报到账了，请查收"% today_time, 'plain', 'utf-8')
    message.attach(message_html)
    message_xlsx = MIMEText(open('weather_today.csv', 'rb').read(), 'base64', 'utf-8')
    message_xlsx['Content-Disposition'] = 'attachment;filename="today_weather.csv"'
    message.attach(message_xlsx)
    message['From'] = FROM
    message['To'] = TO
    message['Subject'] = SUBJECT
    email_client = smtplib.SMTP_SSL(host='smtp.qq.com')
    email_client.connect(HOST, '465')
    result = email_client.login(FROM, '{0}'.format(key))
    print(result)
    email_client.sendmail(from_addr=FROM, to_addrs=TO, msg=message.as_string())
    print("发送成功")
    email_client.close()

get_weather_data()
